package com.ycc.usercenter.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ycc.usercenter.common.ResultUtils;
import com.ycc.usercenter.model.domain.User;
import com.ycc.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private RedissonClient redissonClient;

    // 重点用户
    private List<Long> userList = Arrays.asList(1L);

    @Scheduled(cron = "0 15 12 * * ?")
    private void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock("friendmatch:precachejon:docache:lock");
        try {
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                System.out.println("lock: " + Thread.currentThread().getId());
                // 获取用户列表
                for (Long userId : userList) {
                    String key = String.format("recommend:user_id:%d", userId);
                    ValueOperations valueOperations = redisTemplate.opsForValue();
                    // 判断缓存中是否存在
                    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
                    Page<User> page = userService.page(new Page<>(1, 30), queryWrapper);
                    List<User> list = page.getRecords().stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());
                    page.setRecords(list);
                    // 设置缓存
                    try {
                        valueOperations.set(key, page , 30000, TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        log.error("redis get set error", e);
                    }
                }
            }

        } catch (InterruptedException e) {
            log.error("lock error", e);
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
                System.out.println("unlock: " + Thread.currentThread().getId());
            }
        }
    }
}
